<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<select name="sheng">
			<!-- <option value="1">广东省</option>
			<option value="2">湖南省</option> -->
		</select>
		<select name="shi" hidden>
			<!-- <option value="1">广州市</option>
			<option value="2">中山市</option>
			<option value="3">衡阳市</option>
			<option value="4">长沙市</option> -->
		</select>
		<select name="qu" hidden>
			<option value="1">白云区</option>
			<option value="2">黄埔区</option>
			<option value="3">岳麓区</option>
		</select>
		<script src="../../js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			//1.获取select，然后指定change事件
			$("select[name='sheng']").change(function() {
				console.log($(this).find("option:selected")[0]);
				//获取被选择的option的value和内容
				let option = $(this).find("option:selected");
				//获取内容和值
				let val = option.val(); //值
				let text = option.text(); //内容
				console.log(val, text);

				initSelect("select[name='shi']", shiArr, val);
			});
			$("select[name='shi']").change(function() {
				console.log($(this).find("option:selected")[0]);
				//获取被选择的option的value和内容
				let option = $(this).find("option:selected");
				//获取内容和值
				let val = option.val(); //值
				let text = option.text(); //内容
				console.log(val, text);
			
				initSelect("select[name='qu']", quArr, val);
			});
			/*
				做三级联动，一定要弄清楚以下几点
					1.select标签
					2.jq获取选中的option的val和text
					3.三个select之间的数据必须有关联
			*/
			let shengArr = [{
					id: 1,
					name: "广东省",
					parentId: null
				},
				{
					id: 2,
					name: "湖南省",
					parentId: null
				},
			]
			let shiArr = [{
					id: 1,
					name: "广州市",
					parentId: 1
				},
				{
					id: 2,
					name: "中山市",
					parentId: 1
				},
				{
					id: 3,
					name: "衡阳市",
					parentId: 2
				},
				{
					id: 4,
					name: "长沙市",
					parentId: 2
				}
			]
			
			let quArr = [{
					id: 1,
					name: "白云区",
					parentId: 1
				},
				{
					id: 2,
					name: "黄埔区",
					parentId: 1
				},
				{
					id: 3,
					name: "雁峰区",
					parentId: 3
				},
				{
					id: 4,
					name: "衡阳县",
					parentId: 3
				}
			]
			
			/**
			 * 初始化Select标签内容
			 * @param {Object} selector	选择器
			 * @param {Object} arr		目标数组
			 * @param {Object} parentId	父id
			 */
			function initSelect(selector, arr, parentId) {
				console.log(typeof(parentId) === "string")
				$(selector).empty();
				$(selector).show();
				if(parentId && typeof(parentId) === "string") {
					parentId = parseInt(parentId);
				}
				for (let item of arr) {
					if(parentId && item.parentId !== parentId) {
						continue;
					}
					$(selector).append(`<option value="${item.id}">${item.name}</option>`);
				}
			}

			initSelect("select[name='sheng']", shengArr);
		</script>
	</body>
</html>
